"""
用户管理API
处理用户认证、资料管理等请求
"""

import logging
from flask import request, jsonify, current_app
from . import api_bp
from ..services.user_service import UserService
from ..services.notification_service import NotificationService
from ..utils.auth_utils import require_auth, get_current_user, require_admin
from ..utils.validation_utils import ValidationUtils

logger = logging.getLogger(__name__)

@api_bp.route('/auth/register', methods=['POST'])
def register():
    """
    用户注册
    
    Returns:
        JSON响应包含注册结果
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        username = data.get('username', '').strip()
        email = data.get('email', '').strip()
        password = data.get('password', '')
        
        if not all([username, email, password]):
            return jsonify({'error': '用户名、邮箱和密码不能为空'}), 400
        
        # 创建用户
        user_service = UserService(current_app)
        result = user_service.create_user(username, email, password)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        # 发送欢迎邮件
        try:
            notification_service = NotificationService(current_app)
            notification_service.send_welcome_email(email, username)
        except Exception as e:
            logger.warning(f"发送欢迎邮件失败: {str(e)}")
        
        logger.info(f"用户注册成功: {username} - {email}")
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'user_id': result['user_id']
        }), 201
        
    except Exception as e:
        logger.error(f"用户注册失败: {str(e)}")
        return jsonify({'error': '注册失败，请稍后重试'}), 500

@api_bp.route('/auth/login', methods=['POST'])
def login():
    """
    用户登录
    
    Returns:
        JSON响应包含登录结果和用户信息
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        username = data.get('username', '').strip()
        password = data.get('password', '')
        
        if not all([username, password]):
            return jsonify({'error': '用户名和密码不能为空'}), 400
        
        # 用户认证
        user_service = UserService(current_app)
        result = user_service.authenticate_user(username, password)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 401
        
        logger.info(f"用户登录成功: {result['user']['username']}")
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'user': result['user'],
            'session_token': result['session_token']
        }), 200
        
    except Exception as e:
        logger.error(f"用户登录失败: {str(e)}")
        return jsonify({'error': '登录失败，请稍后重试'}), 500

@api_bp.route('/auth/logout', methods=['POST'])
@require_auth
def logout():
    """
    用户登出
    
    Returns:
        JSON响应包含登出结果
    """
    try:
        current_user = get_current_user()
        if current_user:
            logger.info(f"用户登出: {current_user['username']}")
        
        # TODO: 实现会话令牌失效逻辑
        
        return jsonify({
            'success': True,
            'message': '登出成功'
        }), 200
        
    except Exception as e:
        logger.error(f"用户登出失败: {str(e)}")
        return jsonify({'error': '登出失败'}), 500

@api_bp.route('/user/profile', methods=['GET'])
@require_auth
def get_profile():
    """
    获取用户资料
    
    Returns:
        JSON响应包含用户资料
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取用户资料
        user_service = UserService(current_app)
        result = user_service.get_user_profile(user_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'profile': result['profile']
        }), 200
        
    except Exception as e:
        logger.error(f"获取用户资料失败: {str(e)}")
        return jsonify({'error': '获取用户资料失败'}), 500

@api_bp.route('/user/profile', methods=['PUT'])
@require_auth
def update_profile():
    """
    更新用户资料
    
    Returns:
        JSON响应包含更新结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        # 更新用户资料
        user_service = UserService(current_app)
        result = user_service.update_user_profile(user_id, data)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        logger.info(f"用户资料更新成功: {user_id}")
        
        return jsonify({
            'success': True,
            'message': '资料更新成功'
        }), 200
        
    except Exception as e:
        logger.error(f"更新用户资料失败: {str(e)}")
        return jsonify({'error': '更新资料失败'}), 500

@api_bp.route('/user/password', methods=['PUT'])
@require_auth
def change_password():
    """
    修改密码
    
    Returns:
        JSON响应包含修改结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        old_password = data.get('old_password', '')
        new_password = data.get('new_password', '')
        
        if not all([old_password, new_password]):
            return jsonify({'error': '旧密码和新密码不能为空'}), 400
        
        # 修改密码
        user_service = UserService(current_app)
        result = user_service.change_password(user_id, old_password, new_password)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        logger.info(f"密码修改成功: {user_id}")
        
        return jsonify({
            'success': True,
            'message': '密码修改成功'
        }), 200
        
    except Exception as e:
        logger.error(f"修改密码失败: {str(e)}")
        return jsonify({'error': '修改密码失败'}), 500

@api_bp.route('/user/quota', methods=['GET'])
@require_auth
def get_quota():
    """
    获取用户配额信息
    
    Returns:
        JSON响应包含配额信息
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取配额信息
        user_service = UserService(current_app)
        result = user_service.check_quota(user_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'quota': result['quota_info']
        }), 200
        
    except Exception as e:
        logger.error(f"获取配额信息失败: {str(e)}")
        return jsonify({'error': '获取配额信息失败'}), 500

@api_bp.route('/user/notifications', methods=['GET'])
@require_auth
def get_notifications():
    """
    获取用户通知
    
    Returns:
        JSON响应包含通知列表
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取查询参数
        limit = int(request.args.get('limit', 20))
        offset = int(request.args.get('offset', 0))
        
        if limit > 100:
            limit = 100
        
        # 获取通知
        notification_service = NotificationService(current_app)
        result = notification_service.get_user_notifications(user_id, limit, offset)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'notifications': result['notifications'],
            'total': result['total'],
            'limit': limit,
            'offset': offset
        }), 200
        
    except Exception as e:
        logger.error(f"获取用户通知失败: {str(e)}")
        return jsonify({'error': '获取通知失败'}), 500

@api_bp.route('/user/notifications/<notification_id>/read', methods=['POST'])
@require_auth
def mark_notification_read(notification_id):
    """
    标记通知为已读
    
    Args:
        notification_id: 通知ID
        
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 标记通知为已读
        notification_service = NotificationService(current_app)
        result = notification_service.mark_notification_read(user_id, notification_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': '通知已标记为已读'
        }), 200
        
    except Exception as e:
        logger.error(f"标记通知已读失败: {str(e)}")
        return jsonify({'error': '操作失败'}), 500

@api_bp.route('/user/notifications', methods=['DELETE'])
@require_auth
def clear_notifications():
    """
    清空用户通知
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 清空通知
        notification_service = NotificationService(current_app)
        result = notification_service.clear_user_notifications(user_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': '通知已清空'
        }), 200
        
    except Exception as e:
        logger.error(f"清空通知失败: {str(e)}")
        return jsonify({'error': '操作失败'}), 500

@api_bp.route('/auth/forgot-password', methods=['POST'])
def forgot_password():
    """
    忘记密码
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        email = data.get('email', '').strip()
        
        if not email:
            return jsonify({'error': '邮箱不能为空'}), 400
        
        if not ValidationUtils.validate_email(email):
            return jsonify({'error': '邮箱格式不正确'}), 400
        
        # 请求重置密码
        user_service = UserService(current_app)
        result = user_service.reset_password_request(email)
        
        # 无论用户是否存在，都返回成功消息（安全考虑）
        return jsonify({
            'success': True,
            'message': result['message']
        }), 200
        
    except Exception as e:
        logger.error(f"忘记密码请求失败: {str(e)}")
        return jsonify({'error': '请求失败，请稍后重试'}), 500

@api_bp.route('/auth/reset-password', methods=['POST'])
def reset_password():
    """
    重置密码
    
    Returns:
        JSON响应包含重置结果
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        token = data.get('token', '')
        new_password = data.get('new_password', '')
        
        if not all([token, new_password]):
            return jsonify({'error': '重置令牌和新密码不能为空'}), 400
        
        # 重置密码
        user_service = UserService(current_app)
        result = user_service.reset_password(token, new_password)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': result['message']
        }), 200
        
    except Exception as e:
        logger.error(f"重置密码失败: {str(e)}")
        return jsonify({'error': '重置失败，请稍后重试'}), 500

# 管理员接口
@api_bp.route('/admin/users', methods=['GET'])
@require_admin
def admin_get_users():
    """
    管理员获取用户列表
    
    Returns:
        JSON响应包含用户列表
    """
    try:
        # 获取查询参数
        role = request.args.get('role')
        status = request.args.get('status')
        limit = int(request.args.get('limit', 50))
        offset = int(request.args.get('offset', 0))
        
        if limit > 200:
            limit = 200
        
        # 获取用户列表
        user_service = UserService(current_app)
        result = user_service.list_users(role, status, limit, offset)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'users': result['users'],
            'total': result['total'],
            'limit': limit,
            'offset': offset
        }), 200
        
    except Exception as e:
        logger.error(f"管理员获取用户列表失败: {str(e)}")
        return jsonify({'error': '获取用户列表失败'}), 500

@api_bp.route('/admin/users/<user_id>/ban', methods=['POST'])
@require_admin
def admin_ban_user(user_id):
    """
    管理员禁用用户
    
    Args:
        user_id: 用户ID
        
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        admin_id = current_user['id']
        
        data = request.get_json() or {}
        reason = data.get('reason', '')
        
        # 禁用用户
        user_service = UserService(current_app)
        result = user_service.ban_user(user_id, admin_id, reason)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': '用户已禁用'
        }), 200
        
    except Exception as e:
        logger.error(f"禁用用户失败: {str(e)}")
        return jsonify({'error': '禁用用户失败'}), 500

@api_bp.route('/admin/users/<user_id>/unban', methods=['POST'])
@require_admin
def admin_unban_user(user_id):
    """
    管理员解禁用户
    
    Args:
        user_id: 用户ID
        
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        admin_id = current_user['id']
        
        # 解禁用户
        user_service = UserService(current_app)
        result = user_service.unban_user(user_id, admin_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': '用户已解禁'
        }), 200
        
    except Exception as e:
        logger.error(f"解禁用户失败: {str(e)}")
        return jsonify({'error': '解禁用户失败'}), 500

@api_bp.route('/admin/users/<user_id>', methods=['DELETE'])
@require_admin
def admin_delete_user(user_id):
    """
    管理员删除用户
    
    Args:
        user_id: 用户ID
        
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        admin_id = current_user['id']
        
        # 删除用户
        user_service = UserService(current_app)
        result = user_service.delete_user(user_id, admin_id)
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'message': '用户已删除'
        }), 200
        
    except Exception as e:
        logger.error(f"删除用户失败: {str(e)}")
        return jsonify({'error': '删除用户失败'}), 500

@api_bp.route('/admin/users/statistics', methods=['GET'])
@require_admin
def admin_get_user_statistics():
    """
    管理员获取用户统计信息
    
    Returns:
        JSON响应包含统计信息
    """
    try:
        # 获取用户统计
        user_service = UserService(current_app)
        result = user_service.get_user_statistics()
        
        if not result['success']:
            return jsonify({'error': result['error']}), 400
        
        return jsonify({
            'success': True,
            'statistics': result['statistics']
        }), 200
        
    except Exception as e:
        logger.error(f"获取用户统计失败: {str(e)}")
        return jsonify({'error': '获取统计信息失败'}), 500